<?php

require_once 'Zend/Service/Akismet.php';

class ZFBlog_Validate_Akismet extends Zend_Validate_Abstract
{

    const AKISMET_SPAM = 'akismetSpam';

    protected $_messageTemplates = array(
        self::AKISMET_SPAM => "Akismet thinks you're a spammer!"
    );

    protected static $httpClient = null;

    protected $key = null;

    protected $url = null;

    public static function setHttpClient(Zend_Http_Client $httpClient)
    {
        self::$httpClient = $httpClient;
    }

    public function __construct($key, $url)
    {
        $this->key = $key;
        $this->url = $url;
    }

    public function isValid($value)
    {
        // Grab non-prototyped $context param set from Zend_Form
        $params = func_get_args();
        $context = null;
        if (isset($params[1])) {
            $context = $params[1];
        }
        $akismetData = array(
            'user_ip' => $_SERVER['REMOTE_ADDR'],
            'user_agent' => $_SERVER['HTTP_USER_AGENT'],
            'referrer' => $_SERVER['HTTP_REFERER'],
            'comment_type' => 'comment',
            'comment_author' => $context['name'],
            'comment_author_email' => $context['email'],
            'comment_content' => $context['content']
        );
        $akismet = new Zend_Service_Akismet($this->key, $this->url);
        if (!is_null(self::$httpClient)) {
            self::$httpClient->resetParameters();
            Zend_Service_Akismet::setHttpClient(self::$httpClient);
        }
        if ($akismet->isSpam($akismetData)) {
            $this->_error(self::AKISMET_SPAM);
            return false;
        }
        return true;
    }
}